import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:graduation_project/menu_bar/menu_bar.dart';
import 'dart:convert' as convert;

import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  @override
  LoginPageState createState() => new LoginPageState();
}

class LoginPageState extends State<LoginPage> {
  String loginusername;
  String loginpassword;
  bool loginSate = true;
  String usename;
  SharedPreferences prefs;
  //全局key用来获取From表单组件
  GlobalKey<FormState> loginKey = GlobalKey<FormState>();

  _login() async {
    prefs = await SharedPreferences.getInstance();
    Response response;
    var dio = Dio();
    dio.options.responseType = ResponseType.plain;
    response = await dio.get(
        'http://119.91.231.198:3033/uselogin?loginusername=' +
            loginusername +
            '&loginpassword=' +
            loginpassword);
    print(prefs);
    var res = convert.jsonDecode(response.toString());
    print(res['status']);
    if (res['status'] == 200) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(
          builder: (context) => menu_bar(),
        ),
        (route) => false,
      );
    } else {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              content: Text(
                "登录失败",
                style: TextStyle(color: Colors.black),
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                  textColor: Colors.black54,
                ),
              ],
            );
          });
    }
  }

  _register() async {
    Response response;
    var dio = Dio();
    dio.options.responseType = ResponseType.plain;
    response = await dio.get(
        'http://119.91.231.198:3033/useregister?loginusername=' +
            loginusername +
            '&usename=' +
            usename +
            '&loginpassword=' +
            loginpassword);
    var res = convert.jsonDecode(response.toString());
    print(res);
    if (res['status'] == 200) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(
          builder: (context) => menu_bar(),
        ),
        (route) => false,
      );
    } else {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              content: Text(
                "注册失败",
                style: TextStyle(color: Colors.black),
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                  textColor: Colors.black54,
                ),
              ],
            );
          });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(loginSate ? '登录' : '注册'),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Container(
            child: Image(
              image: NetworkImage(
                  'https://img0.baidu.com/it/u=1861461045,4173684878&fm=253&fmt=auto&app=120&f=JPEG?w=1584&h=800'),
            ),
          ),
          Container(
            padding: EdgeInsets.all(16.0),
            child: Form(
                key: loginKey,
                child: loginSate
                    ? Column(
                        children: <Widget>[
                          TextFormField(
                            decoration: InputDecoration(labelText: '请输入用户名'),
                            onChanged: (value) {
                              loginusername = value;
                            },
                            onFieldSubmitted: (value) {},
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '请输入密码'),
                            obscureText: true,
                            validator: (value) {
                              return value.length < 6 ? '密码长度不够六位' : null;
                            },
                            onChanged: (value) {
                              loginpassword = value;
                            },
                          )
                        ],
                      )
                    : Column(
                        children: [
                          TextFormField(
                            decoration: InputDecoration(labelText: '请输入用户名'),
                            onChanged: (value) {
                              loginusername = value;
                            },
                            onFieldSubmitted: (value) {},
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '请输入用户昵称'),
                            onChanged: (value) {
                              usename = value;
                            },
                            onFieldSubmitted: (value) {},
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: '请输入密码'),
                            obscureText: true,
                            validator: (value) {
                              return value.length < 6 ? '密码长度不够六位' : null;
                            },
                            onChanged: (value) {
                              loginpassword = value;
                            },
                          ),
                        ],
                      )),
          ),
          SizedBox(
            width: 200.0,
            height: 42.0,
            child: RaisedButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: BorderSide(
                  width: 2,
                  color: Colors.red,
                  // style: BorderStyle.solid,
                  style: BorderStyle.none,
                ),
              ),
              onPressed: () {
                if (loginSate) {
                  var loginForm = loginKey.currentState;

                  if (loginForm.validate()) {
                    loginForm.save();
                    _login();
                  }
                } else {
                  setState(() {
                    loginSate = true;
                  });
                }
              },
              child: Text(
                '登录',
                style: TextStyle(fontSize: 18.0),
              ),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          SizedBox(
            width: 200.0,
            height: 42.0,
            child: RaisedButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: BorderSide(
                  width: 2,
                  color: Colors.red,
                  // style: BorderStyle.solid,
                  style: BorderStyle.none,
                ),
              ),
              onPressed: () {
                if (loginSate) {
                  setState(() {
                    loginSate = false;
                  });
                } else {
                  var loginForm = loginKey.currentState;

                  if (loginForm.validate()) {
                    loginForm.save();
                    _register();
                  }
                }
              },
              child: Text(
                '注册',
                style: TextStyle(fontSize: 18.0),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
